package com.faithbj.danaliverpool.web.controller.admin;

import com.faithbj.common.configuration.Pager;
import com.faithbj.common.model.Region;
import com.faithbj.common.model.Roles;
import com.faithbj.common.model.User;
import com.faithbj.common.service.UserService;
import com.faithbj.danaliverpool.service.RoleService;
import com.faithbj.common.service.RegionService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author jrn E-mail: rinanjin@gmail.com
 * @version 0.1 
 * 创建时间：2012-6-8 下午11:39:25
 * 类说明
 */
@Controller
@RequestMapping("/faith/user")
public class AdminUserController extends BaseAdminController
{
	private static final long serialVersionUID = 1L;

	@Resource
	private UserService userService;
	
	@Resource
	private RoleService roleService;
	
	@Resource
	private RegionService regionService;
	
	private final String LIST = "/admin/user_list";
	
	private final String INPUT = "/admin/user_input";
	
	private final String DETAIL = "/admin/user_detail";
	
	private final String PASSWORD = "/admin/user_password_input";
	
	private final String OPERRATE_RETURN_URL = "/faith/user/list";
	
	@RequestMapping(value = "list")
	public String list(@ModelAttribute("pager") Pager pager, ModelMap map)
	{
		Pager pagerVal = userService.findByPager(pager);
		map.put("pager", pagerVal);
		return LIST;
	}
	
	@RequestMapping(value = "add")
	public String add(ModelMap map)
	{
		List<Roles> rolesList = roleService.getAll();
		List<Region> regionList = regionService.getRegionListByCurrentUser();
		
		map.put("rolesList", rolesList);
		map.put("regionList", regionList);
		map.put("isAddAction", true);
		return INPUT;
	}
	
	@RequestMapping(value = "edit")
	public String edit(@RequestParam("id") String id, ModelMap map)
	{
		User user = userService.get(id);
		List<Roles> rolesList = roleService.getAll();
		List<Region> regionList = regionService.getRegionListByCurrentUser();
		// 获取设置用户角色
		Set<Roles> rolesSet = user.getRoles();
		List<String> idList = new ArrayList<String>();
		for(Roles role : rolesSet)
		{
			idList.add(role.getId());
		}
		String[] ids = new String[idList.size()];
		idList.toArray(ids);
		
		map.put("ids", ids);
		map.put("rolesList", rolesList);
		map.put("regionList", regionList);
		map.put("user", user);
		map.put("isAddAction", false);
		return INPUT;
	}
	
	@RequestMapping(value = "update")
	public String update(User user, HttpServletRequest request, ModelMap map)
	{
		// 获取设置用户角色
		List<Roles> rolesList = null;
		String[] ids = request.getParameterValues("ids");
		if(ids.length > 0)
		{
			rolesList = roleService.get(ids);
		}
		
		// 获取用户行政区域
		String regionId = user.getRegion().getId();
		Region region = null;
		if(user.getRegion() != null && StringUtils.hasText(regionId))
		{
			region = regionService.get(regionId);
		}
		user.setRoles(new HashSet<Roles>(rolesList));
		user.setRegion(region);
		user.setOperator(getLoginUser().getUsername());
		userService.update(user);
		userService.flush();
		
		map.put("redirectUrl", OPERRATE_RETURN_URL);
		return SUCCESS;
	}
	
	@RequestMapping(value = "detail")
	public String detail(@RequestParam("id") String id, ModelMap map)
	{
		User user = userService.get(id);
		List<Roles> rolesList = roleService.getAll();
		List<Region> regionList = regionService.getRegionListByCurrentUser();
		// 获取设置用户角色
		Set<Roles> rolesSet = user.getRoles();
		List<String> idList = new ArrayList<String>();
		for(Roles role : rolesSet)
		{
			idList.add(role.getId());
		}
		String[] ids = new String[idList.size()];
		idList.toArray(ids);
		
		map.put("ids", ids);
		map.put("rolesList", rolesList);
		map.put("regionList", regionList);
		map.put("user", user);
		return DETAIL;
	}
	
	@RequestMapping(value = "changepassword")
	public String changePassword(@RequestParam("id") String id, ModelMap map)
	{
		map.put("id", id);
		return PASSWORD;
	}
	
	@RequestMapping(value = "dochangepassword")
	public String doChangePassword(@RequestParam("id") String id, @RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword, ModelMap map)
	{
		User user = userService.get(id);
		if(oldPassword.equals(user.getPassword()))
		{
			user.setPassword(newPassword);
			userService.update(user);
		}
		else
		{
			map.put("error", "原密码不正确");
			return PASSWORD;
		}
		map.put("redirectUrl", OPERRATE_RETURN_URL);
		return SUCCESS;
	}
	
	public String detail(String id)
	{
		return DETAIL;
	}
	
	@RequestMapping(value = "save")
	public String save(@Valid @ModelAttribute("user") User user, Errors errors, ModelMap map, HttpServletRequest request)
	{
		if(userService.get("username", user.getUsername()) != null)
		{
			List<Roles> rolesList = roleService.getAll();
			List<Region> regionList = regionService.getRegionListByCurrentUser();
			
			map.put("error", "该用户名已存在");
			map.put("rolesList", rolesList);
			map.put("regionList", regionList);
			map.put("ids", request.getParameterValues("ids"));
			map.put("isAddAction", true);
			map.put("user", user);
			return INPUT;
		}
		
		if(errors.hasErrors())
		{
			List<Roles> rolesList = roleService.getAll();
			List<Region> regionList = regionService.getRegionListByCurrentUser();
			
			map.put("rolesList", rolesList);
			map.put("regionList", regionList);
			map.put("ids", request.getParameterValues("ids"));
			map.put("isAddAction", true);
			return INPUT;
		}
		// 获取设置用户角色
		List<Roles> rolesList = null;
		String[] ids = request.getParameterValues("ids");
		if(ids.length > 0)
		{
			rolesList = roleService.get(ids);
		}
		
		// 获取用户行政区域
		String regionId = user.getRegion().getId();
		Region region = null;
		if(user.getRegion() != null && StringUtils.hasText(regionId))
		{
			region = regionService.get(regionId);
		}
		user.setRoles(new HashSet<Roles>(rolesList));
		user.setRegion(region);
		user.setOperator(getLoginUser().getUsername());
		user.setAccountNonExpired(true);
		user.setAccountNonLocked(true);
		user.setCredentialsNonExpired(true);
		userService.save(user);
		userService.flush();
		map.put("redirectUrl", OPERRATE_RETURN_URL);
		return SUCCESS;
	}
	
	@RequestMapping(value = "delete")
	public String delete(@RequestParam("id") String id, ModelMap map)
	{
		userService.delete(id);
		userService.flush();
		map.put("redirectUrl", OPERRATE_RETURN_URL);
		return SUCCESS;
	}

	public UserService getUserService()
	{
		return userService;
	}

	public void setUserService(UserService userService)
	{
		this.userService = userService;
	}
}
